#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GIF动画生成示例
演示如何使用水文绘图API生成时间序列动画
"""

import requests
import json
import os
from draw_hydrology_api import plot_hydrology_map

def example_local_gif():
    """使用本地API生成GIF动画的示例"""
    
    print("=== 本地API GIF生成示例 ===")
    
    # 示例1：生成温度变化GIF
    print("\n1. 生成温度变化GIF动画")
    result = plot_hydrology_map(
        nc_filename="chinasea_202212_temp.nc",  # 在GIF模式下会被忽略
        variable="temp",
        title="中国海域温度变化",
        output_filename="temperature_timeseries.gif",
        create_gif=True,
        gif_file_pattern="chinasea_*_temp.nc",  # 匹配所有月份的温度文件
        gif_duration=1.2,  # 每帧1.2秒
        gif_loop=0,  # 无限循环
        gif_vmin=None,  # 自动确定范围，避免异常值
        gif_vmax=None,  # 自动确定范围，避免异常值
        gif_levels=24,  # 24个等值线级别
        gif_integer_levels=True,  # 使用整数级别
        figsize=(14, 10),  # 更大的图像尺寸
        dpi=150,  # 适中的分辨率
        add_north_arrow=True,
        add_scale_bar=True,
        scale_bar_length=300,
        colorbar_extend='both'  # 添加箭头显示超出范围的值
    )
    
    print_result(result, "温度变化GIF")
    
    # 示例2：生成盐度变化GIF（如果有盐度数据）
    print("\n2. 生成盐度变化GIF动画")
    salt_result = plot_hydrology_map(
        nc_filename="chinasea_202212_salt.nc",
        variable="salt",
        title="中国海域盐度变化",
        output_filename="salinity_timeseries.gif",
        create_gif=True,
        gif_file_pattern="chinasea_*_salt.nc",
        gif_duration=1.0,
        gif_loop=0,
        gif_vmin=30,  # 盐度通常在30-35之间
        gif_vmax=35,
        gif_levels=10,
        gif_integer_levels=True,
        figsize=(14, 10),
        dpi=150
    )
    
    print_result(salt_result, "盐度变化GIF")
    
    # 示例3：生成温度+流速的复合GIF
    print("\n3. 生成温度+流速复合GIF动画")
    composite_result = plot_hydrology_map(
        nc_filename="chinasea_202212_temp.nc",
        variable="temp",
        title="中国海域温度和流速变化",
        output_filename="temp_velocity_timeseries.gif",
        create_gif=True,
        gif_file_pattern="chinasea_*_temp.nc",
        uv_nc_filename="chinasea_*_v.nc",  # 对应的流速文件模式
        u_var="u",
        v_var="v",
        gif_duration=1.5,
        gif_loop=0,
        gif_vmin=None,  # 自动确定范围，避免异常值
        gif_vmax=None,  # 自动确定范围，避免异常值
        gif_levels=20,
        gif_integer_levels=True,
        skip_arrows=3,  # 减少箭头密度
        figsize=(16, 12),
        dpi=120,
        colorbar_extend='both'  # 添加箭头显示超出范围的值
    )
    
    print_result(composite_result, "温度+流速复合GIF")


def example_web_api_gif():
    """使用Web API生成GIF动画的示例"""
    
    print("\n=== Web API GIF生成示例 ===")
    
    base_url = "http://localhost:5000"
    
    # 检查API是否可用
    try:
        response = requests.get(f"{base_url}/api/health", timeout=5)
        if response.status_code != 200:
            print("Web API不可用，请先启动web_api.py")
            return
    except requests.RequestException:
        print("Web API不可用，请先启动web_api.py")
        return
    
    print("Web API可用，开始生成GIF...")
    
    # 示例1：通过Web API生成温度GIF
    gif_config = {
        "nc_filename": "chinasea_202212_temp.nc",  # 在GIF模式下会被忽略
        "variable": "temp",
        "title": "中国海域温度变化（Web API生成）",
        "output_filename": "web_temperature_animation.gif",
        "create_gif": True,
        "gif_file_pattern": "chinasea_*_temp.nc",
        "gif_duration": 1.0,
        "gif_loop": 0,
        "gif_vmin": 10,
        "gif_vmax": 30,
        "gif_levels": 20,
        "gif_integer_levels": True,
        "figsize": [14, 10],
        "dpi": 150,
        "add_north_arrow": True,
        "add_scale_bar": True,
        "scale_bar_length": 250
    }
    
    try:
        response = requests.post(
            f"{base_url}/api/plot",
            json=gif_config,
            headers={"Content-Type": "application/json"},
            timeout=300  # 5分钟超时
        )
        
        if response.status_code == 200:
            result = response.json()
            print_result(result, "Web API温度GIF")
            
            # 下载生成的GIF
            if result['status'] == 'success':
                filename = result['data']['download_url'].split('/')[-1]
                download_response = requests.get(f"{base_url}/api/plot/{filename}")
                if download_response.status_code == 200:
                    with open(f"downloaded_{filename}", "wb") as f:
                        f.write(download_response.content)
                    print(f"GIF已下载为: downloaded_{filename}")
        else:
            print(f"Web API请求失败: {response.status_code}")
            print(response.text)
            
    except requests.RequestException as e:
        print(f"Web API请求异常: {e}")


def print_result(result, title):
    """打印结果的辅助函数"""
    print(f"\n{title}:")
    print(f"状态: {result['status']}")
    
    if result['status'] == 'success':
        print(f"输出路径: {result['output_path']}")
        print(f"相对路径: {result['relative_path']}")
        
        metadata = result.get('metadata', {})
        if 'frame_count' in metadata:
            print(f"帧数: {metadata['frame_count']}")
        if 'files_used' in metadata:
            print(f"使用的文件: {metadata['files_used']}")
        if 'duration' in metadata:
            print(f"每帧持续时间: {metadata['duration']}秒")
        if 'value_range' in metadata:
            print(f"数值范围: {metadata['value_range']}")
        if 'integer_levels' in metadata:
            print(f"整数级别: {metadata['integer_levels']}")
            
        # 检查文件是否存在
        if os.path.exists(result['output_path']):
            file_size = os.path.getsize(result['output_path'])
            print(f"文件大小: {file_size / (1024*1024):.2f} MB")
        else:
            print("警告: 输出文件不存在")
    else:
        print(f"错误信息: {result['message']}")


def batch_gif_examples():
    """批量生成多个GIF的示例"""
    
    print("\n=== 批量GIF生成示例 ===")
    
    # 定义多个GIF配置
    gif_configs = [
        {
            "name": "温度变化",
            "config": {
                "nc_filename": "chinasea_202212_temp.nc",
                "variable": "temp",
                "title": "中国海域温度变化",
                "output_filename": "batch_temperature.gif",
                "create_gif": True,
                "gif_file_pattern": "chinasea_*_temp.nc",
                "gif_duration": 1.0,
                "gif_vmin": None,  # 自动确定范围，避免异常值
                "gif_vmax": None,  # 自动确定范围，避免异常值
                "gif_levels": 20,
                "gif_integer_levels": True,
                "colorbar_extend": "both"  # 添加箭头显示超出范围的值
            }
        },
        {
            "name": "流速变化",
            "config": {
                "nc_filename": "chinasea_202212_v.nc",
                "variable": "v",
                "title": "中国海域流速变化",
                "output_filename": "batch_velocity.gif",
                "create_gif": True,
                "gif_file_pattern": "chinasea_*_v.nc",
                "gif_duration": 1.2,
                "gif_vmin": -0.5,
                "gif_vmax": 0.5,
                "gif_levels": 20,
                "gif_integer_levels": False  # 流速使用小数
            }
        }
    ]
    
    # 批量生成GIF
    for i, gif_config in enumerate(gif_configs, 1):
        print(f"\n{i}. 生成{gif_config['name']}GIF")
        result = plot_hydrology_map(**gif_config['config'])
        print_result(result, gif_config['name'])


if __name__ == "__main__":
    print("水文绘图API - GIF动画生成示例")
    print("=" * 50)
    
    # 运行本地API示例
    example_local_gif()
    
    # 运行Web API示例
    example_web_api_gif()
    
    # 运行批量生成示例
    batch_gif_examples()
    
    print("\n" + "=" * 50)
    print("所有示例运行完成！")
    print("生成的GIF文件保存在 'img' 文件夹中") 